package com.ucode.crm.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ucode.crm.dictionary.ContactsShareType;
import com.ucode.crm.dictionary.ModuleType;
import com.ucode.crm.dictionary.TeamUserPower;
import com.ucode.crm.mapper.ContactsMapper;
import com.ucode.crm.mapper.CustomerMapper;
import com.ucode.crm.mapper.FollowupTeamUserMapper;
import com.ucode.crm.mode.Contacts;
import com.ucode.crm.mode.Customer;
import com.ucode.crm.mode.FollowupTeamUser;
import com.ucode.crm.service.ContactsService;
import com.ucode.crm.vo.ContactsVo;
import com.ucode.tool.util.IdentifyUtils;

import cn.hutool.core.collection.CollUtil;

@Service
public class ContactsServiceImpl implements ContactsService {
    
    @Autowired
    private ContactsMapper contactsMapper;
    
    @Autowired
    private CustomerMapper customerMapper;
    
    @Autowired
    private FollowupTeamUserMapper followupTeamUserMapper;
    

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Contacts insert(ContactsVo contactsVo) {
        Contacts contacts = new Contacts(contactsVo.getCustomerId(), contactsVo.getDc(), contactsVo.getName(), contactsVo.getMobile(), 
                contactsVo.getTelephone(), contactsVo.getEmail(), contactsVo.getWechat(), contactsVo.getQq(), 
                contactsVo.getDm(), contactsVo.getJob(), contactsVo.getBirthday(), contactsVo.getSex(), 
                contactsVo.getAddress(), contactsVo.getRemark(), contactsVo.getCreateUserId(),contactsVo.getShareType(), contactsVo.getOwnerUserId());
        contacts.setId(IdentifyUtils.getDefaultSnowflakeId());
        Date now = new Date();
        contacts.setCreatedTime(now);
        contacts.setUpdatedTime(now);
        
        if(contactsMapper.insert(contacts) > 0){
            
            List<FollowupTeamUser> followupTeamUsers = new ArrayList<FollowupTeamUser>();
            //联系人负责人
            FollowupTeamUser contacts_owner_followupTeamUser = new FollowupTeamUser(contacts.getId(), ModuleType.contacts.code, contacts.getOwnerUserId(), TeamUserPower.owner.code);
            contacts_owner_followupTeamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
            contacts_owner_followupTeamUser.setCreatedTime(now);
            contacts_owner_followupTeamUser.setUpdatedTime(now);
            followupTeamUsers.add(contacts_owner_followupTeamUser);
            
            if(ContactsShareType.team.code == contactsVo.getShareType()){
                List<FollowupTeamUser>  list = followupTeamUserMapper.findList(contacts.getCustomerId(), ModuleType.customer.code);
                if(CollUtil.isNotEmpty(list)){
                    for(FollowupTeamUser followupTeamUser : list){
                        if(followupTeamUser.getUserId().equals(contacts.getOwnerUserId()))
                            continue;
                        
                        FollowupTeamUser contacts_followupTeamUser = new FollowupTeamUser(contacts.getId(), ModuleType.contacts.code, followupTeamUser.getUserId(), followupTeamUser.getPower());
                        contacts_followupTeamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
                        contacts_followupTeamUser.setCreatedTime(now);
                        contacts_followupTeamUser.setUpdatedTime(now);
                        followupTeamUsers.add(contacts_followupTeamUser);
                    }
                }
            }else if(ContactsShareType.designator.code == contactsVo.getShareType()){
                List<Long> teamUserIds = contactsVo.getTeamUserIds();
                if(CollUtil.isNotEmpty(teamUserIds)){
                    for(Long userId : teamUserIds){
                        if(userId.equals(contacts.getOwnerUserId()))
                            continue;
                        FollowupTeamUser contacts_followupTeamUser = new FollowupTeamUser(contacts.getId(), ModuleType.contacts.code, userId, TeamUserPower.readWrite.code);
                        contacts_followupTeamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
                        contacts_followupTeamUser.setCreatedTime(now);
                        contacts_followupTeamUser.setUpdatedTime(now);
                        followupTeamUsers.add(contacts_followupTeamUser);
                    }
                }
            }
            
            followupTeamUserMapper.batchSave(followupTeamUsers);
        }
        return contacts;
    }
    
    @Override
    public int update(Contacts contacts) {
        return contactsMapper.update(contacts);
    }

    @Override
    public int updateDc(Long id) {
        Contacts contacts = contactsMapper.findById(id);
        int i = 0;
        if(contacts != null && !contacts.getDc().equals(0)){
            //首要联系人
            Customer customer = customerMapper.findById(contacts.getCustomerId());
            i = contactsMapper.updateDc(customer.getContactsId(), 1);
            customer.setContactsId(contacts.getId());
            customer.setMobile(contacts.getMobile());
            customer.setTelephone(contacts.getTelephone()== null ? "" : contacts.getTelephone());
            customer.setContactsName(contacts.getName()== null ? "" : contacts.getName());
            customer.setContactsSex(contacts.getSex()== null ? 0 : contacts.getSex());
            customerMapper.update(customer);
        }
        return i;
    }

    @Override
    public int updateShareType(Long id, Integer shareType, List<Long> teamUsers) {
        Contacts contacts = contactsMapper.findById(id);
        if(contacts == null)
            return 0;
        
        if(shareType.equals(contacts.getShareType()) && ContactsShareType.owner.code == shareType)
            return 1;
        
        List<FollowupTeamUser> followupTeamUsers = new ArrayList<FollowupTeamUser>();
        
        List<FollowupTeamUser>  contacts_db_followupTeamUsers = followupTeamUserMapper.findList(id, ModuleType.customer.code);
        if(CollUtil.isNotEmpty(contacts_db_followupTeamUsers)){
            List<Long> delIds = new ArrayList<>();
            for(FollowupTeamUser followupTeamUser : contacts_db_followupTeamUsers){
                if(TeamUserPower.owner.code == followupTeamUser.getPower())
                    continue;
                delIds.add(followupTeamUser.getId());
            }
            
            if(delIds.size() > 0)
                followupTeamUserMapper.batchDelete(delIds);
        }
        
        Date now = new Date();
        if(ContactsShareType.team.code == shareType){
            List<FollowupTeamUser>  customer_followupTeamUsers = followupTeamUserMapper.findList(contacts.getCustomerId(), ModuleType.customer.code);
            if(CollUtil.isNotEmpty(customer_followupTeamUsers)){
                for(FollowupTeamUser followupTeamUser : customer_followupTeamUsers){
                    if(followupTeamUser.getUserId().equals(contacts.getOwnerUserId()))
                        continue;
                    
                    FollowupTeamUser contacts_followupTeamUser = new FollowupTeamUser(contacts.getId(), ModuleType.contacts.code, followupTeamUser.getUserId(), followupTeamUser.getPower());
                    contacts_followupTeamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
                    contacts_followupTeamUser.setCreatedTime(now);
                    contacts_followupTeamUser.setUpdatedTime(now);
                    followupTeamUsers.add(contacts_followupTeamUser);
                }
            }
        }else if(ContactsShareType.designator.code == shareType){
            if(CollUtil.isNotEmpty(teamUsers)){
                for(Long userId : teamUsers){
                    if(userId.equals(contacts.getOwnerUserId()))
                        continue;
                    FollowupTeamUser contacts_followupTeamUser = new FollowupTeamUser(contacts.getId(), ModuleType.contacts.code, userId, TeamUserPower.readWrite.code);
                    contacts_followupTeamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
                    contacts_followupTeamUser.setCreatedTime(now);
                    contacts_followupTeamUser.setUpdatedTime(now);
                    followupTeamUsers.add(contacts_followupTeamUser);
                }
            }
        }
        
        if(followupTeamUsers.size() > 0)
            followupTeamUserMapper.batchSave(followupTeamUsers);
        
        return 1;
    }

    @Override
    public int deleteByLogic(Long id) {
        return 0;
    }

    @Override
    public Contacts findById(Long id) {
        return contactsMapper.findById(id);
    }

    @Override
    public List<Contacts> findByIds(List<Long> ids) {
        return contactsMapper.findByIds(ids);
    }

}
